package com.lfy.fyadmin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lfy.fyadmin.common.R;
import com.lfy.fyadmin.entity.Group;
import com.lfy.fyadmin.service.GroupService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/group")
@Tag(name = "用户组管理", description = "用户组相关接口")
public class GroupController {

    private final GroupService groupService;

    public GroupController(GroupService groupService) {
        this.groupService = groupService;
    }

    @PostMapping
    @Operation(summary = "新增用户组")
    public R<Boolean> save(@RequestBody Group group) {
        boolean result = groupService.save(group);
        return result ? R.ok(true) : R.fail("新增失败");
    }

    @PutMapping
    @Operation(summary = "修改用户组")
    public R<Boolean> update(@RequestBody Group group) {
        boolean result = groupService.updateSelective(group);
        return result ? R.ok(true) : R.fail("修改失败");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户组")
    public R<Boolean> delete(@PathVariable Long id) {
        try {
            boolean result = groupService.deleteGroupWithRelations(id);
            return result ? R.ok(true) : R.fail("删除失败");
        } catch (Exception e) {
            return R.fail("删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询用户组")
    public R<Group> getById(@PathVariable Integer id) {
        Group group = groupService.getById(id);
        return group != null ? R.ok(group) : R.fail("未找到用户组");
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询用户组")
    public R<IPage<Group>> findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize) {
        Page<Group> page = new Page<>(pageNum, pageSize);
        return R.ok(groupService.page(page));
    }
}